import { Canvas } from './canvas'
import { Point2D } from './point'
import Circle from './shape/circle'
import Rect from './shape/rect'

const canvas = new Canvas()
canvas.canvas.style.position = 'absolute'
canvas.canvas.style.left = '50%'
canvas.canvas.style.marginLeft = -canvas.canvas.width / 2 + 'px'
// 不要使用transform系列设置canvas，会导致位置计算有误差
// canvas.canvas.style.transform = 'translateX(-50%)'
canvas.canvas.style.border = '1px solid #000'

// 测试10000个矩形的重渲染
for (let i = 0; i < 10; i++) {
  const rect = new Rect(
    (i * Math.random() * 1000) % canvas.canvas.width,
    (i * Math.random() * 1000) % canvas.canvas.height,
    32,
    30,
    '#' + Math.random().toString().substring(2, 8)
  )
  canvas.add(rect)
}

const circle = new Circle({ center: new Point2D(300, 350), radius: 60, fillColor: '#ff00ff' })

const { left, top } = canvas.canvas.getBoundingClientRect()
console.log({ left, top })

circle.on('mousedown', (ev) => {
  const disX = ev.clientX + circle.center.x - canvas.canvas.offsetLeft - circle.radius
  const disY = ev.clientY + circle.center.y - canvas.canvas.offsetTop - circle.radius

  const move = (ev: MouseEvent) => {
    const x = ev.clientX - disX - canvas.canvas.offsetLeft - circle.radius
    const y = ev.clientY - disY - canvas.canvas.offsetTop - circle.radius

    circle.setPosition(x, y)
    canvas.update()
  }

  const up = () => {
    console.log('up')
    document.removeEventListener('mousemove', move)
    document.removeEventListener('mouseup', up)
  }

  document.addEventListener('mousemove', move)
  document.addEventListener('mouseup', up)
})

canvas.add(circle)

const rect = new Rect(200, 350, 50, 50, '#ff00ff')

rect.on('mousedown', (ev) => {
  const disX = ev.clientX - rect.x + canvas.canvas.offsetLeft
  const disY = ev.clientY - rect.y + canvas.canvas.offsetTop

  const move = (ev: MouseEvent) => {
    const x = ev.clientX - disX + canvas.canvas.offsetLeft
    const y = ev.clientY - disY + canvas.canvas.offsetTop

    rect.setPosition(x, y)
    canvas.update()
  }

  const up = () => {
    console.log('up')
    document.removeEventListener('mousemove', move)
    document.removeEventListener('mouseup', up)
  }

  document.addEventListener('mousemove', move)
  document.addEventListener('mouseup', up)
})

canvas.add(rect)

document.body.appendChild(canvas.canvas)
